import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { termite } from "@/api/index";
import store from '../store/index'
import { Dialog } from 'vant'
// import { waitTokenReady } from '@/utils/request'

Vue.use(VueRouter)

const routes = [
  // 根路径重定向
  {
    path: '/',
    redirect: '/onSiteHandling'
  },
  // 现场处理列表
  {
    path: '/onSiteHandling',
    name: 'onSiteHandling',
    component: () => import(/* webpackChunkName: "enterprise" */ '../views/onSiteHandling.vue')
  },
  // 处理
  {
    path: '/handleItem',
    name: 'handleItem',
    component: () => import(/* webpackChunkName: "enterprise" */ '../views/handleItem.vue')
  },
  // 任务单上报
  {
    path: '/reportHome',
    name: 'reportHome',
    component: () => import(/* webpackChunkName: "enterprise" */ '../views/first/index.vue')
  },
  // 历史记录
  {
    path: '/historyRecord',
    name: 'historyRecord',
    component: () => import(/* webpackChunkName: "enterprise" */ '../views/first/historyRecord.vue')
  },
  // 签名
  {
    path: '/signature',
    name: 'signature',
    component: () => import(/* webpackChunkName: "enterprise" */ '../views/first/signature.vue')
  },
  // 白蚁防治企业-基础信息
  {
    path: '/baseMessage',
    name: 'baseMessage',
    component: () => import(/* webpackChunkName: "enterprise" */ '../views/baseMessage.vue')
  },
  // 白蚁防治企业-企业资质
  {
    path: '/qualifiCation',
    name: 'qualifiCation',
    component: () => import(/* webpackChunkName: "enterprise" */ '../views/qualifiCation.vue')
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView
  },
  {
    path: '/enterprise',
    name: 'enterprise',
    // route level code-splitting
    // this generates a separate chunk (enterprise.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "enterprise" */ '../views/Enterprise.vue')
  },
  {
    path: '/my-report',
    name: 'myReport',
    // route level code-splitting
    // this generates a separate chunk (myReport.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "myReport" */ '../views/myReport.vue')
  },
  {
    path: '/termite-report-detail/:id?',
    name: 'termiteReportDetail',
    // route level code-splitting
    // this generates a separate chunk (termiteReportDetail.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "termiteReportDetail" */ '../views/TermiteReportDetail.vue')
  },
  {
    path: '/evaluation/:companyId?',
    name: 'evaluation',
    // route level code-splitting
    // this generates a separate chunk (evaluation.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "evaluation" */ '../views/EvaluationView.vue')
  }
]

const router = new VueRouter({
  routes
})

// 路由前置守卫：确保进入页面前，handleMessage 异步获取的 token 已完成
router.beforeEach(async (to, from, next) => {
  // try {
  //   await waitTokenReady()
  // } catch (e) {
  //   // 忽略等待错误，继续导航
  // }
  if (to.query.data && to.query.encryption && to.query.systemCode) {
    // 手动解析URL参数，处理各种URL编码问题
    const searchParams = window.location.hash.split('?')[1];
    const params = {};
    searchParams.split('&').forEach(param => {
      const [key, value] = param.split('=');
      if (key && value) {
        // 先处理常见的URL编码问题
        let decodedValue = value
          .replace(/%20/g, '+')  // 将%20替换为+（加号）
          .replace(/%2B/g, '+')  // 将%2B替换为+（加号的URL编码）
          .replace(/%26/g, '&')  // 将%26替换为&
          .replace(/%3D/g, '=')  // 将%3D替换为=
          .replace(/%3F/g, '?')  // 将%3F替换为?
          .replace(/%23/g, '#')  // 将%23替换为#
          .replace(/%25/g, '%'); // 将%25替换为%

        // 然后进行URL解码
        params[key] = decodeURIComponent(decodedValue);
      }
    });

    console.log('手动解析的params:', params);

    const data = {
      data: params.data,
      secret: params.encryption,
      sysCode: params.systemCode,
    }
    console.log(data, '处理后的data');
    termite.getTokenNew(data).then((res) => {
      if (res.errorCode === "000000") {
        store.commit("user/SET_USER_INFO", res.data);
        // 系统中用的token
        store.commit("user/SET_TOKEN", res.data.token);
        next()
      }
    });
  } else {
    // 先检查是否已经有token，没有token才提示登录过期
    const existingToken = store.getters['user/token'] || localStorage.getItem('token');
    if (!existingToken) {
      console.log(111);
      Dialog.confirm({
        title: '提示',
        message: '登录已过期，请重新登录',
        confirmButtonText: '重新登录',
        showCancelButton: false
      }).then(() => {
        // 清除本地存储的用户信息
        // localStorage.removeItem('token')
        // localStorage.removeItem('userInfo')
        // store.dispatch('user/logout')
        // console.log('在这里跳转到指定页面');
        // window.location.reload()

        // 跳转到登录页
        // router.replace('/login')
      })
    } else {
      // 如果有token，直接继续导航
      next()
    }
  }
})

export default router
